package com.javaee.ch14.web.api;

import com.javaee.ch14.common.response.ResultVo;
import com.javaee.ch14.service.VerifyCodeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/verify-code")
public class VerifyCodeController {

    @Autowired
    private VerifyCodeService verifyCodeService;

    /**
     * 生成并发送验证码
     * @return 响应信息（演示阶段可返回验证码，实际开发请勿回传验证码给前端！）
     */
    @PostMapping("/generate")
    public ResultVo generate(@RequestBody Map<String, String> phoneMap) {
        String phone = phoneMap.get("phone");
        String code = verifyCodeService.generateCode(phone);

        // *开发/测试环境方便演示返回验证码，正式环境请通过短信发送并隐藏！*
        return ResultVo.ok("验证码已发送（仅测试返回）: " + code);
    }

    /**
     * 校验用户输入的验证码
     */
    @PostMapping("/check")
    public ResultVo check(@RequestBody Map<String, String> map) {
        String phone = map.get("phone");
        String code = map.get("code");
        boolean success = verifyCodeService.verifyCode(phone, code);
        return success ? ResultVo.ok("校验成功") : ResultVo.fail("校验失败或验证码已过期");
    }
}